<template>
  <div>

    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Overview' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>日志表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--    -->
    <el-card class="title">
      <h1>日志表</h1>

    </el-card>
    <el-row>
      <el-col :span="16">
        <div class="block">
          <el-date-picker
            v-model="timeInterval"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </div>
      </el-col>
      <el-col :span="2">
      <el-button type="primary" icon="el-icon-search" @click="doubleRequest">查询</el-button>
      </el-col>
      <el-col :span="2">
        <download-excel
          class = "export-excel-wrapper"
          :data = "exportJson"
          name = "流量日志报告导出.xls">
          <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
          <el-button type="primary">导出EXCEL</el-button>
        </download-excel>
      </el-col>

    </el-row>
    <el-row>
      <el-col :span="4"><el-input v-model="queryInfo.addr" placeholder="请输入用户地址"></el-input></el-col>
      <el-col :span="4"><el-input v-model="queryInfo.protcol" placeholder="请输入用户协议" ></el-input></el-col>
      <el-col :span="4"><el-input v-model="queryInfo.type" placeholder="请输入喜好类型" ></el-input></el-col>
      <el-col :span="4"><el-input v-model="queryInfo.srcPort" placeholder="请输入源端口" type="number"></el-input></el-col>
      <el-col :span="4"><el-input v-model="queryInfo.destPort" placeholder="请输入目的端口" type="number"></el-input></el-col>
    </el-row>


    <!--卡片视图区域-->
    <el-card>
      <TimeLineChart></TimeLineChart>
      <!--用户列表区域-->
      <el-table :data="userlist" border stripe id="out-table" >
        <el-table-column type="index"></el-table-column>
        <el-table-column label="id" prop="id"></el-table-column>
        <el-table-column label="srcAddr" prop="srcAddr"></el-table-column>
        <el-table-column label="destAddr" prop="destAddr"></el-table-column>
        <el-table-column label="srcPort" prop="srcPort"></el-table-column>
        <el-table-column label="destPort" prop="destPort"></el-table-column>
        <el-table-column label="protcolType" prop="protcolType"></el-table-column>
        <el-table-column label="accessTypeId" prop="accessTypeId"></el-table-column>
        <el-table-column label="packSize" prop="packSize"></el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[ 10, 20, 50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </el-card>
  </div>

</template>

<script>
  import FlowChartDataHandle from '../../DataHandle/FlowChartDataHandle'
  import TimeLineChart from '../Overviewchart/TimeLineChart'
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  export default {
    name: 'Log',
    watch:{
      timeInterval(date) {
        this.dateList = []
        let startDay = date[0]
        let endDay = date[1]
        let dateInterval = (endDay - startDay) / 1000 / 60 / 60 / 24 + 1
        let oneDay = 24 * 60 * 60 * 1000
        for (let i = 0; i < dateInterval; i++) {
          let nextDay = startDay.getTime() + oneDay * i
          nextDay = new Date(nextDay)
          this.dateList.push(
            `${nextDay.getFullYear()}-${nextDay.getMonth() +
            1}-${nextDay.getDate()}`
          )
        }
        this.queryInfo.startDateStr = `${startDay.getFullYear()}-${startDay.getMonth() +
        1}-${startDay.getDate()}`;
        this.queryInfo.endDateStr = `${endDay.getFullYear()}-${endDay.getMonth() +
        1}-${endDay.getDate()}`;
      }
    },
    components:{
      TimeLineChart,
    },
    data () {
      return {
        input:null,
        pickerOptions: {
          // disabledDate是一个函数,参数是当前选中的日期值,这个函数需要返回一个Boolean值,
          disabledDate: time => {
            let _now = Date.now()
            let seven = 60 * 24 * 60 * 60 * 1000
            let preSevenDays = _now - seven
            return time.getTime() > _now || time.getTime() < preSevenDays
          },
          onPick: (maxDate, minDate) => {
            maxDate = minDate + 7 * 24 * 60 * 60 * 1000
          }
        }, // 日期设置对象
        timeInterval: '',
        // 获取用户列表的参数对象
        queryInfo: {
          endDateStr:'',
          startDateStr:'',
          addr:'',
          protcol:'',
          type:'',
          srcPort:'',
          destPort:'',
          // 当前的页数
          pagenum: 1,
          // 当前每页显示多少条数据
          pagesize: 5
        },
        userlist: null,
        total: 3,
        // 控制添加用户对话框的显示与隐藏
        addDialogVisble: false,
        // 添加用户的表单数据
        addForm: {
          typeName: '',
          siteName: '',
          ip: '',
          port: ''
        },
        // 控制编辑用户对话框的显示与隐藏
        editDialogVisible: false,
        // 查询到的用户信息对象
        editForm: {},
        // 查询
        query:{
          typeName:'',
          // 当前的页数
          pagenum: 1,
          // 当前每页显示多少条数据
          pagesize: 5
        },
        exportJson:null
      }
    },
    created () {
    },
    methods: {
      async doubleRequest(){
        this.getUserList();
        this.getChartData();
      },
      async getUserList (newPage) {
        let params = new URLSearchParams()
        params.append('addr',this.queryInfo.addr)
        params.append('protcol',this.queryInfo.protcol)
        params.append('type',this.queryInfo.type)
        params.append('srcPort',this.queryInfo.srcPort)
        params.append('destPort',this.queryInfo.destPort)
        params.append('startDateStr',this.queryInfo.startDateStr)
        params.append('endDateStr',this.queryInfo.endDateStr)
        params.append('pagenum', this.queryInfo.pagenum - 1)
        params.append('pagesize', this.queryInfo.pagesize)

        console.log(this.queryInfo)
        let getCapPackMulQueryRes = await this.$http.post(
          '/zz/getCapPackMulQuery',
          params
        )

        if (getCapPackMulQueryRes.data.status !== 200) {
          return this.$message.error('查询失败！')
        }
        let typeJsonRes = await this.$http.post(
          '/accessType/findAllAccessType',
        )
        if (typeJsonRes.data.status !== 200) {
          return this.$message.error('类型查询失败！')
        }

        this.userlist = getCapPackMulQueryRes.data.userCapPackClassifyTran
        console.log(getCapPackMulQueryRes)
        this.total = parseInt(getCapPackMulQueryRes.data.totalNum)
        FlowChartDataHandle.typeJson = typeJsonRes.data
        console.log(new Date(this.queryInfo.startDateStr))
      },
      async getChartData(){
          let params = new URLSearchParams()
          params.append('addr',this.queryInfo.addr)
          params.append('protcol',this.queryInfo.protcol)
          params.append('type',this.queryInfo.type)
          params.append('srcPort',this.queryInfo.srcPort)
          params.append('destPort',this.queryInfo.destPort)
          params.append('startDateStr',this.queryInfo.startDateStr)
          params.append('endDateStr',this.queryInfo.endDateStr)
          let getCapPackMulQueryRes2 = await this.$http.post(
            '/zz/getCapPackMulQueryEx',
            params
          )
          if (getCapPackMulQueryRes2.data.status !== 200) {
            return this.$message.error('查询失败！')
          }
          this.exportJson = getCapPackMulQueryRes2.data.userCapPackClassify
          let resDate =
            FlowChartDataHandle.tran(getCapPackMulQueryRes2.data,FlowChartDataHandle.typeJson,
              new Date(this.queryInfo.startDateStr),0
            )
          this.$Pubsub.publish("timeLineData",resDate[1])
      },
      // 监听 pagesize 改变事件
      handleSizeChange (newSize) {

        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 监听页码值改变的事件
      handleCurrentChange (newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // 监听添加用户对话框的关闭事件
      addDialogClosed () {
        this.$refs.addFormRef.resetFields()
      },
      exportExcel () {
        /* generate workbook object from table */
        var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
        /* get binary string as output */
        var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
        } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
        return wbout
      },

      // 展示用户编辑的对话框
      async showEditDialog (id) {
        let params = new URLSearchParams()
        params.append('id',id)
        let getCapPackClassifyForDateRes = await this.$http.post(
          '/accessType/findOneAccessTypeById',
          params
        )
        console.log(getCapPackClassifyForDateRes)
        if (getCapPackClassifyForDateRes.data.status !== 200) {
          return this.$message.error('查询用户信息失败！')
        }
        console.log(getCapPackClassifyForDateRes.data)
        this.editForm = getCapPackClassifyForDateRes.data.accessType[0]
        this.editDialogVisible = true
      },
      // 监听修改用户对话框的关闭事件
      editDialogClosed () {
        this.$refs.editFormRef.resetFields()
      },
      // 修改用户信息并提交
      async editUserInfo () {
        // 发起修改用户信息的请求
        // const {data: res} = await this.$http.put('UserRuleTable/' + this.editForm.id, {
        //   email: this.editForm.email,
        //   mobile: this.editForm.mobile
        // })
        //
        // if(res.meta.status !== 200) {
        //   return this.$message.error('更新用户信息失败')
        // }
        console.log(this.editForm.id)
        let params = new URLSearchParams()
        params.append('id',this.editForm.id)
        params.append('typeName', this.editForm.typeName)
        params.append('siteName', this.editForm.siteName)
        params.append('ip', this.editForm.ip)
        params.append('port', this.editForm.port)
        console.log(params)
        console.log(this.addForm)
        let getCapPackClassifyForDateRes = await this.$http.post(
          '/accessType/updateAccessType',
          params
        )
        console.log(getCapPackClassifyForDateRes)
        if (getCapPackClassifyForDateRes.data.status !== 200) {
          return this.$message.error('更新失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新信息成功')
      },
      // 根据Id删除对应的用户信息
      async removeUserById (id) {
        // console.log(id)
        // 询问用户是否删除
        const confirmResult = await this.$confirm('此操作将永久删除该条信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async (success) => {
          let params = new URLSearchParams()
          params.append('id',id)
          let getCapPackClassifyForDateRes = await this.$http.post(
            '/accessType/delAccessType',
            params
          )
          console.log(getCapPackClassifyForDateRes)
          if (getCapPackClassifyForDateRes.data.status !== 200) {
            return this.$message.error('查询用户信息失败！')
          }

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserList()

          return success
        }).catch((err) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
          return err
        })
        console.log(confirmResult)
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
